/* eslint-disable no-unused-vars */
/**
 * 登录授权相关的接口定义(示例代码，开发者可以自定义)
 * @Author: bobo
 * @Date: 2021-02-01 
 * 异步函数
 * https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function
 */
import apiHelper from '@/api/api-helper'
import store from '@/store'
import JSEncrypt from 'jsencrypt'
import DynaRouterUtil from "@/utils/DynaRouterUtil";
import {
  DefaultRoutes,
  DynamicRoutesMap
} from "@/router";
const URL_LOGIN = "/console/admin/login";
const URL_REFRESH_TOKEN = "/console/admin/token-refresh";
const PUB_KEY = "-----BEGIN PUBLIC KEY-----MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgGLHLSBdS0waflUq6ot6lSOIk8ky3pIMI8ZUrpAFqncw083lPImWOpZ7LHOoqW2eHgRICu58K69kFSY1RJt5ko9CmO0MG4E6erUV7ODB0+k+IXVjcV4LBQuSw5dJCDz9RF8UplYmOxFaTMaeddJsV40QDJTHa5IhKg4LAuCTIJ0PAgMBAAE=-----END PUBLIC KEY-----";

function _handleLoginSuccess(data) {
  store.oauth().saveAccessToken(data.oauth.accessToken, 1.5 * 60 * 60)
  store.oauth().saveRefreshToken(data.oauth.refreshToken, 15 * 24 * 60 * 60)
  store.user().setUserName(data.user.name)
  store.user().setUserAccount(data.user.account)
  store.user().setExtra(data.user)
  store.user().flushDisk();
}

export default {
  /**
   * 用户登录
   * @param {String} acc  账号
   * @param {String} pwd  密码
   * @param router v-router路由实例
   */
  async login(acc, pwd, router) {
    var encryptor = new JSEncrypt();
    encryptor.setPublicKey(PUB_KEY) //设置公钥
    var rsaPassWord = encryptor.encrypt(pwd); // 对内容进行加密
    var config = {
      headers: {
        NeedToken: false
      },
      params: {
        account: acc,
        password: rsaPassWord,
      },
    };
    const res = await apiHelper.post(URL_LOGIN, {}, config, MOCK_LOGIN_DATA)
    console.log("登录响应数据:", res)
    if (res.errcode === 0) {
      _handleLoginSuccess(res.data)
      console.log("动态路由初始化=====>start")
      //获取动态路由，并初始化
      const routes = await this.getDynaRouters();
      const roles = [];
      res.data.user.roles.forEach(element => {
        roles.push(element.code)
      });
      console.log("用户角色:", roles)
      //初始化动态路由
      DynaRouterUtil.initDynamicRoutes(DefaultRoutes, routes, roles, router);
      console.log("动态路由初始化=====>end")
    }
    return res;
  },
  /**
   * 刷新token
   */
  refreshToken() {
    let _refreshToken = store.oauth().getRefreshToken();
    if (_refreshToken == null) {
      return Promise.resolve("");
    } else {
      const config = {
        headers: {
          NeedToken: false
        },
        params: {
          refreshToken: _refreshToken
        }
      };
      return apiHelper.get(URL_REFRESH_TOKEN, config, MOCK_REFRESH_TOKEN);
    }
  },
  /**
   * 获取本地缓存access_token
   * axios拦截器中使用异步方法的解决方式
   * @return {Promise} 授权token
   */
  async getAccessToken() {
    //1.本地缓存获取
    let accessToken = store.oauth().getAccessToken();
    if (accessToken != null && accessToken != '') {
      return Promise.resolve(accessToken);
    }
    //2.接口中获取
    const response = await this.refreshToken();
    console.log("refresh-token:", response)
    if (response.errcode == 0) {
      store.oauth().saveAccessToken(response.data.accessToken, response.data.expiresIn - 60);
      return Promise.resolve(response.data.accessToken)
    } else {
      return Promise.resolve("");
    }
  },
  /**
   * 获取动态路由
   */
  async getDynaRouters() {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(DynamicRoutesMap);
      }, 100);
    });
  }
}


//mock-data 
const MOCK_LOGIN_DATA = {
  "errcode": 0,
  "errmsg": "操作成功",
  "data": {
    "user": {
      "avatar": null,
      "account": "admin",
      "name": "管理员",
      "roles": [{
        "name": "超级管理员",
        "code": "role_admin"
      }],
    },
    "oauth": {
      "accessToken": "43fe58e7-925e-4c65-915f-8a982090fe4c",
      "refreshToken": "28da76b4-14d9-4f46-8d27-2edfa922c9ad",
      "expiresIn": 7199,
      "scope": 'all',
      "tokenType": "bearer"
    }
  }
};
const MOCK_REFRESH_TOKEN = {
  "errcode": 0,
  "errmsg": "success",
  "data": {
    "accessToken": "3b8a0c83-d4fb-40ed-a640-15b31658bc90",
    "refreshToken": "28da76b4-14d9-4f46-8d27-2edfa922c9ad",
    "expiresIn": 6787,
    "scope": null,
    "tokenType": "bearer"
  }
}